import json

from django.core.handlers.wsgi import WSGIRequest
from django.utils.deprecation import MiddlewareMixin
import time
import logging

from rest_framework.response import Response


# 请求相应日志记录
class LogsMiddleware(MiddlewareMixin):
    start = 0

    # 请求
    def process_request(self, request):
        self.start = time.time()

    # 响应  get请求如果没有带最后的斜杠 '/' 会发两次请求，第一次响应状态码是404，第二次是为后面自动添加一个斜杠'/'
    def process_response(self, request, response):
        logger = logging.getLogger("log")
        req: WSGIRequest = request
        res: Response = response

        param = ''
        if req.method == 'GET':
            param = req.GET
        elif req.method == 'POST':
            try:
                param = json.loads(req.body.decode())
            except:
                pass
        logger.info(f"""
============================================================
请求用户：{req.user.username}
请求路径：{req.path}
请求方式：{req.method}
请求参数：{param}
耗时时间：{str(time.time() - self.start)}
响应状态：{res.status_code}

============================================================
                """)

        return res
